#!/bin/bash

set -ux

echo '确保每个节点上 MAC 地址和 product_uuid 的唯一性'
# ip link
# cat /sys/class/dmi/id/product_uuid

echo '允许 iptables 检查桥接流量'
# 确保 br_netfilter 模块被加载。这一操作可以通过运行 lsmod | grep br_netfilter 来完成。若要显式加载该模块，可执行  modprobe br_netfilter
lsmod | grep br_netfilter &&
  lsmod | grep overlay &&
  modprobe overlay &&
  modprobe br_netfilter

cat <<EOF | tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF

# 设置必需的 sysctl 参数，这些参数在重新启动后仍然存在。
cat <<EOF | tee /etc/sysctl.d/k8s.conf
# 开启数据包转发功能
net.ipv4.ip_forward                 = 1
# iptables对bridge的数据进行处理
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF

# 应用 sysctl 参数而无需重新启动
sysctl --system

# 安装依赖
dnf install -y iproute-tc nmap-ncat \
  ipset vim ipvsadm wget bash-completion \
  device-mapper-persistent-data lvm2

#  修改systemd 默认使用 cgroup v2
# dnf install -y grubby &&
#   grubby \
#     --update-kernel=ALL \
#     --args="systemd.unified_cgroup_hierarchy=1"

# 关闭防火墙
systemctl stop firewalld && systemctl disable firewalld

# 禁用swap
swapoff -a && sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

# 关闭selinux
setenforce 0 &&
  sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config

# 设置时区
timedatectl set-timezone Asia/Shanghai &&
  timedatectl set-local-rtc 0 &&
  systemctl restart rsyslog &&
  systemctl restart crond

# 时间同步'
dnf install -y chrony &&
  systemctl enable chronyd &&
  systemctl start chronyd &&
  chronyc -a makestep

echo '安装 kubeadm、kubelet 和 kubectl'
cat >/etc/yum.repos.d/kubernetes.repo <<EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

dnf install -y kubelet kubeadm kubectl
systemctl enable --now kubelet &&
  systemctl restart kubelet

echo "清除缓存"
dnf clean all
